// 引入接口文件
import {giftRegAdd,giftRegEdit,getUserDetail,getGiftDetail,getRegion,getProject,giftDelete,queryUserRegion} from './giftRegistrationDetailServ.js'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import { isEmpty, isArray, cloneDeep, merge } from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'
import Cookie from 'js-cookie'
import config from 'config/config'

import { calculate_object_name } from 'utils/upload'
import { makeAddress } from "utils/util"

// 初始默认状态
const defultState = {
	loading: false,
	btnLoading: false,
	isSubmit:true,
	actionType:'',
	regionList:[],
	projectList:[],
	levelInfoList:[
		{name:'集团',value:'3',code:'1001'},
		{name:'区域',value:'2',code:'1002'},
		{name:'项目',value:'1',code:'1004'},
	],
	filterInfoList:[],
	detail: {
		shelfStatus: 1,
		isSelfTemplate: false,
		activityCoverImg:'',
		startOnlineTime:moment().format('YYYY-MM-DD 00:00:01'),
		endOnlineTime:moment().add(1,"months").format('YYYY-MM-DD 23:59:59'),
		startOfflineTime:moment().format('YYYY-MM-DD 00:00:01'),
		endOfflineTime:moment().add(1,"months").format('YYYY-MM-DD 23:59:59'),
		totalStockType:1,
		totalStock:1,
		limitCount:1,
		limitCountType:1,
		productType:undefined,
		productUsage:undefined,
		reginonName:undefined,
		reginonId:undefined,
		projectId:undefined,
		projectName:undefined,
		updatePerson:undefined,
		detail:undefined,
		usageScope:undefined,
	},
	levelList:{
		'1001':'1001',
		'1002':'1002',
		'1003':'1003',
		'1004':'1004'
	}
}

// 声明module
const tmpModule = {
	// 默认状态
	state: cloneDeep(defultState),
	// 入口函数(先执行)
	subscriptions: {
		setup({ dispatch, history }) {
			history.listen(({ pathname, query }) => {
				// 页面路由匹配时执行
				if ('' + tmpModule.pathname === '' + pathname) {
					
				    dispatch({ type: 'getUserDetail', payload: {}})
					dispatch({ type: 'queryUserRegion', payload: {} })
					dispatch({ type: 'updateStore', payload: { actionType: query.actionType } })
					if(query.actionType=='add'){
						dispatch({ type: 'updateStore', payload: { detail: cloneDeep(defultState).detail } })
					}
					if(query.actionType=='edit' || query.actionType=='look'){
						dispatch({ type: 'getGiftDetail', payload: {...query} })
					}
				} // end if
			}) // end listen
		},
	},
	// 方法列表
	effects: {
		*getUserDetail({ payload }, { put, call, select }) {
			let isAdmin = JSON.parse(localStorage.getItem('navBar')).accountId || ''
			//账户是admin就直接返回 集团级权限
			if (isAdmin == '1') {
				defultState.filterInfoLis = [
					{name:'集团',value:'3',code:'1001'},
					{name:'区域',value:'2',code:'1002'},
					{name:'项目',value:'1',code:'1004'},
				]
				yield put({ type: 'updateStore', payload: { filterInfoList: defultState.filterInfoLis } })
			}else {
				try {
					yield put({ type: 'updateStore', payload: { btnLoading: true } })
					let accountId = Cookie.get(config.cookie.userId);
					const {success,data} = yield call(getUserDetail, {accountId})
					if(success){
						let roleLevel = []
						data.roleList.forEach(item=>{
							if(defultState.levelList[item.permissionRoleId]){
								roleLevel.push(item.permissionRoleId)
							}
						})
						console.log(roleLevel)
						let maxLevel = Math.min(...roleLevel)
						defultState.filterInfoList = defultState.levelInfoList.filter(item=>{
							return Number(item.code)>= maxLevel
						})
						console.log(defultState.filterInfoList)
						yield put({ type: 'updateStore', payload: { filterInfoList: defultState.filterInfoList } })
					}
					yield put({ type: 'updateStore', payload: { btnLoading: false } })
				}catch (e) {
	
				}
			}
			
		},
		*submit({ payload }, { put, call, select }) {
			try {
				yield put({ type: 'updateStore', payload: { btnLoading: true } })
				let { detail, actionType } = yield select((state) => state[tmpModule.namespace])
				const server = actionType == 'add'?giftRegAdd:giftRegEdit
				if(actionType=='add'){
					detail.createPerson = localStorage.getItem('username')
				}else{
					detail.updatePerson = localStorage.getItem('username')
				}
				const { success } = yield call(server, { ...detail });
				if(success){
					message.success('保存成功');
					hashHistory.push('/home/infoAdmin/giftRegistrationList')
				}else{
					message.warning('保存失败');
				}
				yield put({ type: 'updateStore', payload: { btnLoading: false } })
				console.log('detail',detail)
			}catch (e) {
				console.log(e)
			}
		},
		*queryUserRegion({ payload }, { put, call, select }) {
			try {
				let accountId = JSON.parse(localStorage.getItem('navBar')).accountId || ""
				let {success,rows} = yield call(queryUserRegion, {accountId})
				if(success){
					let regionList = rows
					regionList.forEach((item,index)=>{
						item.value = item.regionId
						item.label = item.regionName
						item.key = index
					})
					yield put({ type: 'updateStore', payload: { regionList:regionList } })
				}
			}catch(e){

			}
		},
		*getGiftDetail({ payload }, { put, call, select }) {
			try {
				const data = yield call(getGiftDetail, {...payload })
				if (data.success) {
					let detail = data.data
					yield put({ type: 'updateStore', payload: { detail } })
					if(detail.regionId){
						const data = yield call(getProject, {regionId:detail.regionId})
						let projectList = data.rows
						yield put({ type: 'updateStore', payload: { projectList } })
					}
				}
			} catch (e) {
			}
		},
		*giftDelete({ payload }, { put, call, select }){
			try {
				const data = yield call(giftDelete, {...payload })
				if (data.success) {
					message.warning('删除成功');
					hashHistory.push('/home/infoAdmin/giftRegistrationList')
				}
			} catch (e) {

			}
		}
	},

	// 存入状态机
	reducers: {
		updateStore(preState, action) {
			return Object.assign({}, preState, action.payload)
		},
	}
}

export default tmpModule
